<template>
  <div class="security-login">
    <a-tabs
      v-model:activeKey="activeKey"
      style="
        margin-top: -30px;
        width: 40%;
        min-width: 500px;
        max-width: 700px;
        box-shadow: 0px 0px 50px 10px rgba(0, 0, 0, 0.05);
        border-radius: 5px;
        padding: 20px;
        height: 480px;
      "
    >
      <a-tab-pane key="1" tab="登录">
        <a-form
          ref="formRef"
          :model="user"
          :rules="rules"
          :wrapper-col="wrapperCol"
        >
          <h1
            style="
              text-align: center;
              font-family: 楷体;
              font-size: 60px;
              font-weight: bold;
              color: rgba(0, 0, 0, 0.6);
              margin: 30px auto;
            "
          >
            云易染信息系统
          </h1>
          <a-form-item name="u_id">
            <a-input v-model:value="user.u_id">
              <template #prefix>账号：</template>
            </a-input>
          </a-form-item>

          <a-form-item name="u_pwd">
            <a-input-password v-model:value="user.u_pwd">
              <template #prefix>密码：</template>
            </a-input-password>
          </a-form-item>

          <a-form-item :wrapper-col="wrapperCol" style="padding-bottom: 50px">
            <a-button type="primary" block @click="login">登录</a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" tab="注册">
        <a-form
          ref="registerRef"
          :model="newUser"
          :rules="rules"
          :wrapper-col="wrapperCol"
        >
          <h1
            style="
              text-align: center;
              font-family: 楷体;
              font-size: 50px;
              font-weight: bold;
              color: rgba(0, 0, 0, 0.6);
              margin: 0px auto;
            "
          >
            注册新用户
          </h1>
          <a-form-item name="u_id">
            <a-input v-model:value="newUser.u_id">
              <template #prefix>账号：</template>
            </a-input>
          </a-form-item>

          <a-form-item name="u_name">
            <a-input v-model:value="newUser.u_name">
              <template #prefix>姓名：</template>
            </a-input>
          </a-form-item>

          <a-form-item name="u_pwd">
            <a-input-password v-model:value="newUser.u_pwd">
              <template #prefix>密码：</template>
            </a-input-password>
          </a-form-item>
          <a-form-item name="u_pwd2">
            <a-input-password v-model:value="newUser.u_pwd2">
              <template #prefix>确认密码：</template>
            </a-input-password>
          </a-form-item>

          <a-form-item :wrapper-col="wrapperCol" style="padding-bottom: 50px">
            <a-button type="primary" block @click="regist">注册</a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script setup>

import { ref, reactive } from "vue";

//引入自定义封装的函数或对象
import { post, setLocalToken, tip } from "@/common";

import { useRouter } from "vue-router";

const router = useRouter(); //获取路由器

const activeKey = ref("1");//ref函数用于将数封装为单向绑定（数据-》界面）

const formRef = ref();//此变量会自动与元素中ref="formRef"产生关联，以后此变量就表示元素对象
const registerRef = ref();

//reactive函数用于将数据封装为双向绑定（数据《==》界面）
const user = reactive({
  u_id: "",
  u_pwd: "",
});

const newUser = reactive({
  u_id: "",
  u_pwd: "",
  u_pwd2:""
});

const validatePwd2 = async (rule, value) => {
  
      if (value === '') {
        return Promise.reject('请输入确认密码！');
      } else if (value !== newUser.u_pwd) {
        return Promise.reject("两次输入密码不一致!");
      } else {
        return Promise.resolve();
      }
    };

const rules = {
  u_id: [
    {
      required: true,
      message: "请输入账号！",
      trigger: "blur",
    },
    {
      min: 3,
      max: 10,
      message: "账号必须为3~10个字符构成！",
      trigger: "blur",
    },
  ],
  u_name:[
    {
      required: true,
      message: "请输入姓名！",
      trigger: "blur",
    },
  ],
  u_pwd: [
    {
      required: true,
      message: "请输入密码！",
      trigger: "blur",
    },
  ],
  u_pwd2: [
    {
      validator: validatePwd2,
      trigger: "blur",
    },
  ],
};

const login = () => {
  formRef.value
    .validate()
    .then(() => {
      //then方法仅接收成功操作的结果
      post("/security/login", user).then((res) => {
        tip.success("登录成功！");

        const token = res.data; //获取返回的令牌

        //将令牌存储于本地
        setLocalToken(token);

        //跳转至/home路由

        // //路由传复杂对象示例
        // const obj = {
        //   a:123,b:"测试",c:{x:123,y:456}
        // }
        // const jsonStr = JSON.stringify(obj);//将对象转为字符串
        // const encodedStr = encodeURIComponent(jsonStr);//字符串作为 URI 组件进行编码

        // router.push({ path: "/home", query:{data:encodedStr}});
        router.push({ path: "/home"});


      });
    })
    .catch((error) => {
      tip.error("输入信息缺失或不正确！");
    });
};

const regist = () => {
  registerRef.value
    .validate()
    .then(() => {
      //then方法仅接收成功操作的结果
      post("/security/login/regist", newUser).then((res) => {
        tip.success("注册成功！请登录。");
        activeKey.value = '1';        
      });
    })
    .catch((error) => {
      tip.error("输入信息缺失或不正确！");
    });
};

//一行24列
const wrapperCol = {
  offset: 5,
  span: 14,
};
</script>

<style scoped>
.security-login {
  position: fixed;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>